import {
  reqGetCode,
  reqUserRegister,
  reqUserLogin,
  reqUserInfo,
  reqLogout,
} from "@/api/index";
import { setToken,removeToken } from "@/utils/token";

const state = {
  code: "",
  token:localStorage.getItem("TOKEN"),
  userInfo: "",
};
const mutations = {
  GETCODE(state, data) {
    state.code = data;
  },
  //   登录
  USERLOGIN(state, token) {
    state.token = token;
  },
  //   获取用户信息
  GETUSERINFO(state, data) {
    // state.token = getToken
    state.userInfo = data;
  },
  //   清除本地数据
  CLEAR(state) {
    state.token = "";
    state.userInfo = "";
    removeToken();
  },
};
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone);
    if (result.code == 200) {
      commit("GETCODE", result.data);
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  // 用户注册
  async UserRegister({ commit }, user) {
    let result = await reqUserRegister(user);
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  //   登录
  async UserLogin({ commit }, user) {
    let result = await reqUserLogin(user);
    if (result.code == 200) {
      // 持久化存储token
      commit("USERLOGIN", result.data.token);
      setToken(result.data.token);
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  //   获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqUserInfo();
    if (result.code == 200) {
      commit("GETUSERINFO", result.data);
      return "ok";

    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  //   退出登录
  async userLogout({ commit }) {
    let result = await reqLogout();
    if (result.code == 200) {
      commit("CLEAR");
      return "ok"
    }else{
        return Promise.reject(new Error(result.message))
    }
  },
};
const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
